/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.aptech.bluepumpkin.beans;

import com.aptech.bluepumpkin.Users;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

/**
 *
 * @author Trong Nguyen
 */
@Stateless
public class UsersFacade extends AbstractFacade<Users> {
    @PersistenceContext(unitName = "BluePumkin-ejbPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public UsersFacade() {
        super(Users.class);
    }
    public boolean findUserByUserName(String username){
        TypedQuery<Users> query = em.createNamedQuery("Users.findByUsername", Users.class);
        query.setParameter("username", username);
        List<Users> resultList = query.getResultList();
        if(null!=resultList){
            if(resultList.size()>0){
                return true;
            }
        }
        return false;
       
    }
     public Users checkEmail(String email) {
        Query createNamedQuery = em.createNamedQuery("Users.findByEmail",Users.class);
        createNamedQuery.setParameter("email", email);
        return (Users) createNamedQuery.getSingleResult();
        
    }

    public Users checkLogin(Users user) {
        String hql = "SELECT u FROM Users u WHERE u.userName = :userName AND u.passWord = :passWord";
        Query query = em.createQuery(hql);
        query.setParameter("userName", user.getUsername());
        query.setParameter("passWord", user.getPassword());
        return (Users) query.getSingleResult();
    }

    public List<Users> getAllUserWithBirhday() {

        Calendar cal = Calendar.getInstance();

        int day = cal.get(Calendar.DAY_OF_MONTH);
        int month = cal.get(Calendar.MONTH) + 1;
        Query createQuery = em.createNamedQuery("Users.findByIsActive");
        createQuery.setParameter("isActive", true);

        List<Users> resultList = createQuery.getResultList();

        List<Users> users = new ArrayList<Users>();
        for (Users user : resultList) {
            if (null != user.getDob()) {
                cal.setTime(user.getDob());
                int day_us = cal.get(Calendar.DAY_OF_MONTH);
                int month_us = cal.get(Calendar.MONTH) + 1;
                if (day == day_us && month == month_us) {
                    users.add(user);
                }
            }
        }

        return users;
    }
}
